package com.whfc.common.third.mas.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.whfc.common.exception.BizException;
import com.whfc.common.third.mas.MasProperties;
import com.whfc.common.third.mas.MasProjectApi;
import com.whfc.common.third.mas.entity.ProjectInfoListRequest;
import com.whfc.common.third.mas.entity.ProjectInfoListResponse;
import com.whfc.common.third.mas.entity.ProjectDetailResponse;
import com.whfc.common.third.mas.entity.MeasurePointListResponse;
import com.whfc.common.util.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.whfc.common.result.ResultEnum;
import java.util.HashMap;
import java.util.Map;

/**
 * MAS项目信息API实现类
 */
@Component
public class MasProjectApiImpl implements MasProjectApi {

    private static final Logger logger = LoggerFactory.getLogger(MasProjectApiImpl.class);

    private final MasProperties masProperties;

    public MasProjectApiImpl(MasProperties masProperties) {
        this.masProperties = masProperties;
    }

    @Override
    public ProjectInfoListResponse listProjectInfo(String saToken, String name) throws BizException {
        logger.info("MAS系统查询项目信息，name:{}", name);

        // 构建完整的请求URL
        String url = masProperties.getApiUrl() + (masProperties.getApiUrl().endsWith("/") ? "" : "/")
                + "API/mas/project/projectInfo/list";

        // 构建请求参数
        ProjectInfoListRequest request = new ProjectInfoListRequest();
        request.setName(name);
        String requestBody = JSON.toJSONString(request);

        // 构建请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("satoken", saToken);
        headers.put("Content-Type", "application/json");

        try {
            // 发送POST请求，使用配置的超时时间
            String response = HttpUtil.doPost(url, requestBody, headers,
                    masProperties.getConnectTimeout(), masProperties.getReadTimeout());
            logger.info("MAS系统项目信息查询响应: {}", response);

            // 解析响应结果
            ProjectInfoListResponse projectResponse = JSONObject.parseObject(response, ProjectInfoListResponse.class);

            // 检查响应是否成功
            if (projectResponse == null) {
                throw new BizException(ResultEnum.FAILURE.getCode(), "MAS系统项目信息查询失败，响应数据为空");
            }

            if (projectResponse.getCode() == null || projectResponse.getCode() != 200) {
                throw new BizException(ResultEnum.FAILURE.getCode(),
                        projectResponse.getMsg() != null ? projectResponse.getMsg() : "MAS系统项目信息查询失败");
            }

            return projectResponse;
        } catch (BizException e) {
            logger.error("MAS系统项目信息查询异常: {}", e.getMessage());
            throw e;
        } catch (Exception e) {
            logger.error("MAS系统项目信息查询异常: {}", e.getMessage(), e);
            throw new BizException(ResultEnum.FAILURE.getCode(), "MAS系统项目信息查询失败，请稍后重试");
        }
    }

    @Override
    public ProjectDetailResponse getProjectDetail(String saToken, Integer projectId) throws BizException {
        logger.info("MAS系统查询项目详情，projectId:{}", projectId);

        if (projectId == null || projectId <= 0) {
            throw new BizException(ResultEnum.PARAM_ERROR.getCode(), "项目ID不能为空且必须为正数");
        }

        // 构建完整的请求URL
        String url = masProperties.getApiUrl() + (masProperties.getApiUrl().endsWith("/") ? "" : "/")
                + "API/mas/project/projectInfo/detail?id=" + projectId;

        // 构建请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("satoken", saToken);
        headers.put("Content-Type", "application/json");

        try {
            // 发送GET请求，使用配置的超时时间
            String response = HttpUtil.doGet(url, null, headers,
                    masProperties.getConnectTimeout(), masProperties.getReadTimeout());
            logger.info("MAS系统项目详情查询响应: {}", response);

            // 解析响应结果
            ProjectDetailResponse projectDetailResponse = JSONObject.parseObject(response, ProjectDetailResponse.class);

            // 检查响应是否成功
            if (projectDetailResponse == null) {
                throw new BizException(ResultEnum.NETWORK_ERROR.getCode(), "MAS系统项目详情查询失败，响应数据为空");
            }

            if (projectDetailResponse.getCode() == null || projectDetailResponse.getCode() != 200) {
                throw new BizException(ResultEnum.FAILURE.getCode(),
                        projectDetailResponse.getMsg() != null ? projectDetailResponse.getMsg() : "MAS系统项目详情查询失败");
            }

            return projectDetailResponse;
        } catch (BizException e) {
            logger.error("MAS系统项目详情查询业务异常: {}", e.getMessage());
            throw e;
        } catch (Exception e) {
            logger.error("MAS系统项目详情查询系统异常: {}", e.getMessage(), e);
            // 根据异常类型判断是否为超时错误
            String errorMessage = "MAS系统项目详情查询失败，请稍后重试";
            String errorCode = ResultEnum.NETWORK_ERROR.getCode();

            // 检查异常消息中是否包含超时相关关键词
            if (e.getMessage() != null && (e.getMessage().contains("timeout") || e.getMessage().contains("超时"))) {
                errorCode = ResultEnum.NETWORK_TIMEOUT.getCode();
                errorMessage = "MAS系统项目详情查询超时，请稍后重试";
            }

            throw new BizException(errorCode, errorMessage);
        }
    }

    @Override
    public MeasurePointListResponse listMeasurePoints(String saToken, Integer projectId) throws BizException {
        logger.info("MAS系统查询测点名册列表，projectId:{}", projectId);

        // 参数校验
        if (projectId == null || projectId <= 0) {
            throw new BizException(ResultEnum.PARAM_ERROR.getCode(), "项目ID不能为空且必须为正整数");
        }

        // 构建完整的请求URL，使用GET请求，将projectId作为查询参数
        String url = masProperties.getApiUrl() + (masProperties.getApiUrl().endsWith("/") ? "" : "/")
                + "API/mas/project/measurePoint/list?projectId=" + projectId;

        // 构建请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("satoken", saToken);
        headers.put("Content-Type", "application/json");

        try {
            // 发送GET请求，使用配置的超时时间
            String response = HttpUtil.doGet(url, null, headers,
                    masProperties.getConnectTimeout(), masProperties.getReadTimeout());
            logger.info("MAS系统测点名册列表查询响应: {}", response);

            // 解析响应结果
            MeasurePointListResponse measurePointResponse = JSONObject.parseObject(response,
                    MeasurePointListResponse.class);

            // 检查响应是否成功
            if (measurePointResponse == null) {
                throw new BizException(ResultEnum.FAILURE.getCode(), "MAS系统测点名册列表查询失败，响应数据为空");
            }

            if (measurePointResponse.getCode() == null || measurePointResponse.getCode() != 200) {
                throw new BizException(ResultEnum.FAILURE.getCode(),
                        measurePointResponse.getMsg() != null ? measurePointResponse.getMsg() : "MAS系统测点名册列表查询失败");
            }

            return measurePointResponse;
        } catch (BizException e) {
            logger.error("MAS系统测点名册列表查询异常: {}", e.getMessage());
            throw e;
        } catch (Exception e) {
            logger.error("MAS系统测点名册列表查询异常: {}", e.getMessage(), e);
            throw new BizException(ResultEnum.FAILURE.getCode(), "MAS系统测点名册列表查询失败，请稍后重试");
        }
    }
}